#!/bin/bash

source ./conf/build.config

becho()
{
    if [[ $1 == "-n" ]]; then
        echo -ne "\033[1m$2\033[0m"
    else
        echo -e "\033[1m$1\033[0m"
    fi
}

untar()
{
    if [[ $1 =~ .tar.bz2 ]]; then
        pkg=$(echo $1 | awk -F'.tar.bz2' '{printf("%s\n", $1) }')
        [[ ! -d $pkg ]] && tar -jxf $1
    elif [[ $1 =~ .tar.gz ]]; then
        pkg=$(echo $1 | awk -F'.tar.gz' '{printf("%s\n", $1) }')
        [[ ! -d $pkg ]] && tar -zxf $1
    elif [[ $1 =~ .tgz ]]; then
        pkg=$(echo $1 | awk -F'.tgz' '{printf("%s\n", $1) }')
        [[ ! -d $pkg ]] && tar -zxf $1
    fi
    echo -n $pkg
}

download()
{
    file=`basename $1`
    if [[ ! -f $SRCDIR/$file ]]; then
        wget -q $1
        [[ $? -ne 0 ]] && echo -n 2 || echo -n 0
    else
        echo -n 1
    fi
}

#removes man pages and doc file, strips binaries 
clean_dir()
{
    DIR=$1

    find $DIR -name \*.la -o -name \*.a -exec rm -f {} \;
    find $DIR -type d -name .svn | xargs rm -rf
    find $DIR -type d -name man | xargs rm -rf
    find $DIR -type d -name doc | xargs rm -rf
    find $DIR -type d -name locale | xargs rm -rf

    echo "Strip libraries in $DIR"
    find $DIR -name \*.so -exec strip -d {} \;

    echo "Strip binaries in $DIR"
    if [[ -d $DIR/usr/bin ]]; then
        OLDIFS=$IFS
        IFS=$'\n'
        arr=( $(find $DIR/usr/bin -type f | xargs file | grep ELF | awk -F':' '{print $1}') )
        IFS=$OLDIFS
        for n in `seq 0 $(( ${#arr[@]} - 1 ))`; do
            strip -s ${arr[$n]}
        done
    fi

    if [[ -d $DIR/usr/sbin ]]; then
        OLDIFS=$IFS
        IFS=$'\n'
        arr=( $(find $DIR/usr/sbin -type f | xargs file | grep ELF | awk -F':' '{print $1}') )
        IFS=$OLDIFS
        for n in `seq 0 $(( ${#arr[@]} - 1 ))`; do
            strip -s ${arr[$n]}
        done
    fi

    if [[ -d $DIR/bin ]]; then
        OLDIFS=$IFS
        IFS=$'\n'
        arr=( $(find $DIR/bin -type f | xargs file | grep ELF | awk -F':' '{print $1}') )
        IFS=$OLDIFS
        for n in `seq 0 $(( ${#arr[@]} - 1 ))`; do
            strip -s ${arr[$n]}
        done
    fi

    if [[ -d $DIR/sbin ]]; then
        OLDIFS=$IFS
        IFS=$'\n'
        arr=( $(find $DIR/sbin -type f | xargs file | grep ELF | awk -F':' '{print $1}') )
        IFS=$OLDIFS
        for n in `seq 0 $(( ${#arr[@]} - 1 ))`; do
            strip -s ${arr[$n]}
        done
    fi
}


build_pkg()
{
    #save the values in an array
    OLDIFS=$IFS
    IFS=$'\n'
    arr=()
    arr=( $(echo $1 | awk -F';' '{ for(i=1; i<=NF; i++) { print $i } }') )
    IFS=$OLDIFS

    local n=1
    local name=${arr[0]}
    local version=${arr[1]}
    local url=${arr[2]}

    echo -n "Build Step [$n]: "
    echo -n "Downloading $url ... "
    ret=$(download $url)
    if [[ $ret -eq 2 ]]; then
        echo "Failed to download" 
        return 0 
    elif [[ $ret -eq 1 ]]; then
        echo "already downloaded"
    else
        echo "downloaded"
    fi

    (( n++ ))
    echo -n "Build Step [$n]: "
    file=$(basename $url)
    echo -n "Unpacking $file source ... "
    pkg=$(untar $file)
    if [[ ! -d $pkg ]]; then
        echo "Failed to unpack" 
        return 0 
    else
        echo "done"
    fi

    echo '' > $LOGDIR/${APP}_${pkg}.log
    cd $pkg
    for n in `seq 3 $(( ${#arr[@]} - 1))`; do
        echo '#!/bin/bash' > run.sh
        inst=${arr[$n]}
        echo -n "Build Step [$n]: '$inst' ... "
        echo "" >> $LOGDIR/${APP}_${pkg}.log
        echo "Build Step [$n]: '$inst'" >> $LOGDIR/${APP}_${pkg}.log
        echo "" >> $LOGDIR/${APP}_${pkg}.log
        echo $inst >> run.sh
        sh run.sh >> $LOGDIR/${APP}_${pkg}.log 2>&1
        if [[ $? -ne 0 ]]; then
            echo "Failed"
            return
        else
            echo "Success"
        fi
    done
    rm -f run.sh
    cd ..
    clean_dir $STAGING/$APP/$name
    #rm -rf $pkg
}

build_rpm()
{
    local name=$1
    local version=$2


    #if a specfile already exist for this pkg, use it, otherwise create one based on template
    if [[ ! -f $APPDIR/$APP/$name.spec ]]; then
        echo -n "Creating spec file for pkg $name of app $APP ... "
        sed -e "s!APP!$APP!" -e "s!NAME!$name!" -e "s!VERSION!$version!" $BLDDIR/template.spec > $APPDIR/$APP/${name}_tmp.spec
        echo "Success"
    else 
        sed -e "s!APP!$APP!" $APPDIR/$APP/$name.spec > $APPDIR/$APP/${name}_tmp.spec
    fi

    cd $ROOT
    echo -n "Building rpm for $name.$version ... "
    if [[ ! -d $STAGING/$APP/$name ]]; then
        echo "Cannot find dir $name."
    else
        rpmbuild -bb --buildroot $STAGING/$APP/$name $APPDIR/$APP/${name}_tmp.spec > $LOGDIR/${APP}_${name}_rpm.log 2>&1
        if [[ $? -ne 0 ]]; then
            echo "Failed"
        else
            echo "Success"
        fi
    fi
    #rm -f $APPDIR/$APP/${name}_tmp.spec
}

install_rpm()
{

    if [[ $1 =~ "^/" ]]; then
        file=$1
        shift
        if [[ ! -f $file ]]; then
            echo "Cannot install rpm. $file not found"
            return -1
        fi

        echo -n "Installing $file ... "
        rpm -i --root $ROOTFS $file $@

        if [[ $? -ne 0 ]]; then
            echo "Failed"
        else
            echo "Success"
        fi
        return
    fi

    OLDIFS=$IFS
    IFS=$'\n'
    arr=( $(find $MNTPNT -regex "$MNTPNT/$1-[0-9].*" -type f) )
    IFS=$OLDIFS
    tmp=""

    if [[ ${#arr[@]} -eq 0 ]]; then
        echo "Cannot install rpm. $1 not found"
        return
    fi
    for n in `seq 0 $(( ${#arr[@]} - 1))`; do
        file=${arr[n]}
        if [[ $file =~ $ARCH ]]; then
            tmp=$file
            break
        fi
    done
    if [[ $tmp != "" ]]; then
        file=$tmp
    fi

    if [[ ! -f $file ]]; then
        echo "Cannot install rpm. $file not found"
        return -1
    fi

    echo -n "Installing $file ... "
    rpm -i --root $ROOTFS $file --nodeps --nosignature
    if [[ $? -ne 0 ]]; then
        echo "Failed"
    else
        echo "Success"
    fi
    return 0
}

remove_rpm()
{
    echo -n "Removing $file ... "
    rpm -e --root $ROOTFS $file $@

    if [[ $? -ne 0 ]]; then
        echo "Failed"
    else
        echo "Success"
    fi
    return
}

mount_cd()
{
    link="/dev/"$(readlink /dev/cdrom)

    if [[ `cat /proc/mounts | grep $link` ]]; then
        echo "Already mounted"
    else
        echo -n "Mounting $link ... "
        mount $link /mnt
        echo "Done"
    fi
}

#build the pkgs specified in the pkglist.
build_pkg_list()
{
    cd $ROOT
    sed -e "s!STAGING!$STAGING/$APP!g" -e "s!ARCH!$ARCH!g" $1 > pkglist.tmp
    becho "Build pkgs in $1 ..."
    while read i
    do
        cd $SRCDIR
        if [[ $i =~ "^#" || $i =~ "^$" ]]; then
            continue
        fi

        build_pkg "$i"
    done < pkglist.tmp
    rm -f pkglist.tmp
}

#build the rpms specified in the rpmlist. If the pkg build off src tarball
#exists then the rpm is build for that, else the system rpm is used
build_rpm_list()
{
    cd $ROOT
    becho "Build rpms in $1 ..."
    while read i
    do
        cd $SRCDIR
        if [[ $i =~ "^#" || $i =~ "^$" ]]; then
            continue
        fi

        OLDIFS=$IFS
        IFS=$'\n'
        arr=( $(echo $i | awk -F';' '{ for(i=1; i<=NF; i++) { print $i } }') )
        IFS=$OLDIFS
        name=${arr[0]}
        version=${arr[1]}

        if [[ $name == "" ]]; then
            echo "build_rpm: specify something to build "
            continue
        fi
        if [[ ! -d $STAGING/$APP/$name ]]; then
            echo "build_rpm: No build dir present for pkg $name, using system rpm"
            continue
        fi
        if [[ $version == "" ]]; then
            echo "build_rpm: No version present for pkg $name, using system rpm"
            continue
        fi

        build_rpm $name $version
        cp -f $STAGING/RPMS/$ARCH/$name-$version-1.$ARCH.rpm $APP_REPO
    done < $1
}

#install rpm from the specified list either from the staging area or the install CD.
install_rpm_list()
{
    if [[ ! -f $1 ]]; then
        return
    fi

    mount_cd

    cd $ROOT
    sed -e "s!STAGING!$STAGING!g" -e "s!ARCH!$ARCH!g" $1 > rpmlist.tmp
    becho "Install rpms listed in $1 to $ROOTFS"
    while read j
    do
    if [[ $j =~ "^#" ]]; then
        continue
    fi

    OLDIFS=$IFS
    IFS=$'\n'
    arr=( $(echo $j | awk -F';' '{ for(i=1; i<=NF; i++) { print $i } }') )
    IFS=$OLDIFS
    name=${arr[0]}

    f=$(find $STAGING/RPMS -type f -name \*${name}\*)
    if [[ -f $f ]]; then
        install_rpm $f --nodeps
    else
        yum --disablerepo=\* --enablerepo=cd --installroot=$ROOTFS install -y $name
    fi

    done < rpmlist.tmp
    rm -f rpmlist.tmp
}
